// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CommandBinding.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon.Windows.Input.Commands
{
    using System;
    using System.Windows.Input;

    public class CommandBinding
    {
        #region Fields

        private readonly ICommand _command;
        private readonly EventHandler<ExecuteCommandEventArgs> _execute;
        private readonly EventHandler<CanExecuteCommandEventArgs> _canExecute;

        #endregion

        public CommandBinding(ICommand command, EventHandler<ExecuteCommandEventArgs> executed) :
            this(command, executed, null)
        {
        }

        public CommandBinding(ICommand command, EventHandler<ExecuteCommandEventArgs> execute, 
            EventHandler<CanExecuteCommandEventArgs> canExecute)
        {
            #region Validate Arguments

            Guard.ArgumentNull("command", command);

            #endregion

            _command = command;
            _execute = execute;
            _canExecute = canExecute;
        }

        public ICommand Command
        {
            get { return _command; }
        }

        internal void Execute(object parameter)
        {
            if (CanExecute(parameter))
            {
                var handler = _execute;
                if (handler != null)
                {
                    handler(this, new ExecuteCommandEventArgs(_command, parameter));
                }
            }
        }

        internal bool CanExecute(object parameter)
        {
            if (_execute == null)
            {
                return false;
            }

            if (_canExecute == null)
            {
                return true;
            }

            var args = new CanExecuteCommandEventArgs(_command, parameter);
            _canExecute(this, args);
            return args.CanExecute;
        }
    }
}